<template>
	<div class="padding-across-10">
		<div style="width: 100%">
			<headerOpreate style="padding-bottom: 2px;float: left" :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
			<div class="block" style="text-align:right;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
		</div>
		<el-table border style="width: 100%" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" type="index" align="center"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" :label="$t('message.name')" align="center" prop="Name"></el-table-column>
			<el-table-column :show-overflow-tooltip="true" :label="$t('message.edit')" align="center">
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="editTemplate(scope.row)"><i class="el-icon-edit el-icon--left"></i>{{$t('message.opreateEdit')}}</el-button>
				</template>
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" :label="$t('message.downloadExcelTemplate')" align="center">
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="downloadTemplate(scope.row)"><i class="fa fa-download" style="padding-right: 2px;font-size: 12px;"></i>{{$t('message.download')}}</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="block" style="text-align:right;margin-bottom:60px">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
			</el-pagination>
		</div>
		<!-- 创建与修改模板 -->
		<el-dialog :title="dialogTitle" v-model="orderDialog" :class="[dialog-large-width]">
			<el-form :model="editForm" ref="editForm" label-width="100px" class="demo-form">
				<el-form-item :label="$t('message.title')" prop="Title" :rules="[{ required: true, message: $t('message.titleRule'), trigger: 'blur' }]">
					<el-input v-model="editForm.Title" style="max-width:640px"></el-input>
				</el-form-item>
				<el-form-item :label="$t('message.operation')">
					<div v-if="editForm.isLock" style="color:#f34b4b;">
						{{$t('message.itPreventsAnyOperationsAsThisTemplateHasBeenUsed')}}
					</div>
					<div v-else>
						<el-button size="small" type="primary" @click="addLine">{{$t('message.insertRow')}}</el-button>
						<el-button size="small" type="danger" @click="deleteLine">{{$t('message.deleteRow')}}</el-button>
					</div>
				</el-form-item>
				<el-form-item :label="$t('message.timeTable')">
					<el-table :data="editForm.orders" border style="width: 100%" @selection-change="handleSelectionChange">
						<el-table-column :show-overflow-tooltip="true" type="selection" width="55"></el-table-column>
						<el-table-column :show-overflow-tooltip="true" :label="$t('message.courseSequence')" align="center">
							<template slot-scope="scope">
								<div>{{scope.row.Name}}</div>
							</template>
						</el-table-column>
						<el-table-column :show-overflow-tooltip="true" :label="$t('message.start')" align="center">
							<template slot-scope="scope">
								<el-time-picker v-model="scope.row.StartTime" :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" :placeholder="$t('message.pleaseSelectTime')"></el-time-picker>
							</template>
						</el-table-column>
						<el-table-column :show-overflow-tooltip="true" :label="$t('message.end')" align="center">
							<template slot-scope="scope">
								<el-time-picker v-model="scope.row.EndTime" :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" :placeholder="$t('message.pleaseSelectTime')"></el-time-picker>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="orderDialog = false">取 消</el-button>
				<el-button type="danger" v-if="editForm.isLock===false && editForm.CourseOrderId" @click="deleteTemplate">删 除</el-button>
				<el-button type="primary" @click="saveSubmit">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'
	export default {
		components: {
			headerOpreate
		},
		data() {
			Date.prototype.Format = function(fmt) { //author: meizz 
				var o = {
					"Y+": this.getYear(), //年份
					"M+": this.getMonth() + 1, //月份 
					"d+": this.getDate(), //日 
					"h+": this.getHours(), //小时 
					"m+": this.getMinutes(), //分 
					"s+": this.getSeconds(), //秒 
					"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
					"S": this.getMilliseconds() //毫秒 
				};
				if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				for(var k in o)
					if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			}
			return {
				orderDialog: false,
				dialogTitle: '',
				editForm: {},
				defaultData: {
					Title: '',
					orders: [{
						"Name": "1",
						"StartTime": "",
						"EndTime": ""
					}, {
						"Name": "2",
						"StartTime": "",
						"EndTime": ""
					}],
					isLock: ''
				},
				tableData: [],
				multipleSelection: [],
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				opreateDatas: [{
					show: true,
					size: "small",
					type: 'primary',
					icon: 'el-icon-eleg-icon_refresh el-icon--left',
					name: '刷新',
					action: 'reloadDatas'
				},
				{
					show: true,
					size: "small",
					type: "primary",
					icon: "el-icon-plus",
					name: this.$t('message.add'),
					action: "addTemplate"
				}
				]
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			addTemplate() {
				this.orderDialog = true;
				this.dialogTitle = '添加模板';
				this.editForm = this.defaultData;
				var now = new Date(),
				y = now.getFullYear(),
				m = now.getMonth() + 1,
				d = now.getDay();
				this.defaultData.orders.forEach(function(item) {
					switch(item.Name) {
						case "1":
						item.StartTime = new Date(y, m, d, '08', '30', '00');
						item.EndTime = new Date(y, m, d, '09', '30', '00');
						break;
						case "2":
						item.StartTime = new Date(y, m, d, '09', '30', '00');
						item.EndTime = new Date(y, m, d, '10', '30', '00');
						break;
					}
				});
			},
			editTemplate(row) {
				// console.log(row)
				this.orderDialog = true;
				this.dialogTitle = '编辑模板';
				HttpServer.httpGet.call(this, '/Api/CourseOrder/' + row.CourseOrderId, function(response) {}, function(response) {
					// console.log(response)
					response.data.orders = this.formatDate(response.data.orders);
					this.editForm = response.data;
					this.editForm.isLock = response.data.isLock;
					this.editForm.Title = row.Name;
					this.editForm.CourseOrderId = row.CourseOrderId;
				});
			},
			saveSubmit() {
				this.$refs["editForm"].validate((valid) => {
					if(valid) {
						var parmas = {
							Name: this.editForm.Title,
							Orders: this.reverseFormatDate(this.editForm.orders),
							UserId: parseInt(GloabFun.getKeyId())
						}
						if(this.editForm.CourseOrderId) {
							//编辑
							parmas.Id = this.editForm.CourseOrderId;
							// console.log(parmas)
							HttpServer.httpPost.call(this, '/Api/CourseOrder/Put', parmas, function(response) {}, function(response) {
								if(response.data.code === 0) {
									this.$notify({
										title: '成功',
										message: this.$t('message.saveSuccess'),
										type: 'success',
										duration: 2500
									});
									this.getDatas();
									this.orderDialog = false;
								} else {
									this.$notify.error({
										title: '错误',
										message: response.data.msg,
										duration: 2500
									});
								}
							});
						} else {
							//新增
							HttpServer.httpPost.call(this, '/Api/CourseOrder/Post', parmas, function(response) {}, function(response) {
								if(response.data.code === 0) {
									this.$notify({
										title: '成功',
										message: this.$t('message.saveSuccess'),
										type: 'success',
										duration: 2500
									});
									this.getDatas();
									this.orderDialog = false;
								} else {
									this.$notify.error({
										title: '错误',
										message: response.data.msg,
										duration: 2500
									});
								}
							});
						}
					} else {
						return false;
					}
				});
			},
			deleteTemplate() {
				this.$confirm(this.$t('message.deltetTemplateAlert'), this.$t('message.warning'), {
					confirmButtonText: this.$t('message.yes'),
					cancelButtonText: this.$t('message.no'),
					type: 'warning'
				}).then(() => {
					HttpServer.httpPost.call(this, '/Api/CourseOrder/Delete', {
						UserId: parseInt(GloabFun.getKeyId()),
						keyid: [this.editForm.CourseOrderId]
					}, function(response) {}, function(response) {
						if(response.data.code === 0) {
							this.$notify({
								title: '成功',
								message: this.$t('message.deleteSuccess'),
								type: 'success',
								duration: 2500
							});
							this.orderDialog = false;
							this.getDatas();
						} else {
							this.$notify.error({
								title: '错误',
								message: response.data.msg,
								duration: 2500
							});
						}
					});
				}).catch(() => {
					this.$notify.info({
						title: '消息',
						message: this.$t('message.cancleOperation'),
						duration: 2500
					})
				});
			},
			formatDate(array) {
				var now = new Date(),
				y = now.getFullYear(),
				m = now.getMonth() + 1,
				d = now.getDay();
				array.forEach(function(item) {
					var stArray = item.StartTime.split(":");
					item.StartTime = new Date(y, m, d, stArray[0], stArray[1], stArray[2]);
					stArray = item.EndTime.split(":");
					item.EndTime = new Date(y, m, d, stArray[0], stArray[1], stArray[2]);
				});
				return array;
			},
			addLine() {
				if(this.editForm.orders.length > 0) {
					var index = this.editForm.orders.length - 1,
					num = parseInt(this.editForm.orders[index].Name) + 1;
					this.editForm.orders.push({
						Name: num + '',
						StartTime: '',
						EndTime: ''
					});
				} else {
					this.editForm.orders.push({
						Name: '1',
						StartTime: '',
						EndTime: ''
					});
				}
			},
			deleteLine() {
				if(this.multipleSelection.length > 0) {
					//删除处理
					var that = this;
					this.multipleSelection.forEach(function(item) {
						var index = that.editForm.orders.indexOf(item);
						if(index !== -1) {
							that.editForm.orders.splice(index, 1);
						}
					});
					this.editForm.orders.forEach(function(item, index) {
						item.Name = index + 1;
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: this.$t('message.deleteChooseTheRowAlert'),
						type: 'warning',
						duration: 2500
					});
				}
			},
			reverseFormatDate(array) {
				// console.log(array)
				array.forEach(function(item) {
					item.StartTime = item.StartTime.Format('hh:mm:ss');
					item.EndTime = item.EndTime.Format('hh:mm:ss');
					// item.StartTime=item.StartTime.getHours()+":"+item.StartTime.getMinutes()+":"+item.StartTime.getSeconds();
					// item.EndTime=item.EndTime.getHours()+":"+item.EndTime.getMinutes()+":"+item.EndTime.getSeconds();
				});
				return array;
			},

			handleSizeChange(val) {
				this.pageSize = val;
				this.getDatas();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDatas();
			},
			downloadTemplate(row) {
				window.location.href = localHost + "/Api/CourseOrder/" + row.CourseOrderId + "/Excel";
			},
			//刷新
			reloadDatas() {
				HttpServer.httpGet.call(this, '/Api/CourseOrder?page=' + this.currentPage + '&size=' + this.pageSize + '&filter=&access_token=' + GloabFun.getToken(), function(response) {}, function(response) {
					if(response.data.code === 0) {
						this.tableData = response.data.data;
						this.totalSize = response.data.total;
						this.$notify({
							title: '成功',
							message: this.$t('message.refreshSuccess'),
							type: 'success',
							duration: 2500
						});
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			},
			getDatas() {
				HttpServer.httpGet.call(this, '/Api/CourseOrder?page=' + this.currentPage + '&size=' + this.pageSize + '&filter=&access_token=' + GloabFun.getToken(), function(response) {}, function(response) {
					// console.log('模板列表',response)
					if(response.data.code === 0) {
						this.tableData = response.data.data;
						this.totalSize = response.data.total;
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
				});
			}
		},
		created() {
			this.getDatas();
			this.$nextTick(function() {});
		}
	}
</script>